<template>
    <div style=" position: relative;">

        <!-- 搜索 -->
        <div>
            <el-input clearable style="width:220px" v-model="find_data.trustCompanyName" placeholder="被托管单位名称">
            </el-input>

            <el-select multiple collapse-tags v-model="find_data.trustStatusList" :placeholder="'托管状态'"
                style="width: 220px;margin-left: 10px;">
                <el-option label="未回复" value="NOT_REPLY" />
                <el-option label="同意" value="AGREED" />
                <el-option label="拒绝" value="REFUSED" />
                <el-option label="已取消" value="CANCELED" />
            </el-select>

            <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;" v-model="timeTypeTime"
                @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />

            <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                icon="Search">搜索</el-button>
        </div>
        <!-- 功能按钮 -->
        <div style="margin-top:10px;display: flex;margin-bottom:10px;">
            <el-button @click="add_btn" type="primary" icon="SuccessFilled">申请托管</el-button>
            <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
            <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
            <el-button @click="cancelTrusteeshipRecord_btn" type="danger">取消托管申请</el-button>
        </div>

        <div>
            <el-table border @selection-change="selection_change_btn" height="61vh" ref="multipleTableRef"
                :data="list_data" style="width: 100%" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column type="selection" width="35" />
                <el-table-column label="编号" width="55" fixed type="index" />
                <template v-for="item in table_data_list_new" :key="item.field">
                    <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">


                        <template v-if="item.field == 'trustStatus'" #="{ row, column, $index }">


                            <span>{{ row.trustStatus == 'NOT_REPLY' ? '未回复' : row.trustStatus == 'AGREED' ? '同意' :
                                row.trustStatus
                                    == 'REFUSED' ? '拒绝' : row.trustStatus == 'CANCELED' ? '已取消' : '' }}</span>

                        </template>
                    </el-table-column>
                </template>


            </el-table>
        </div>

        <div style="margin-top:20px">
            <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                :page-sizes="[100, 200, 300, 500]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                :total="total" />
        </div>

    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:50px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="170px" label-suffix="：">
                <el-form-item label="被托管方单位名称" :required="false">
                    <el-select @change='cusCompany_change' clearable style="width: 350px;" filterable remote
                        :filter-method="cusOptions_handleFilter" v-model="add_data.trustUserId"
                        placeholder="请选择被托管方单位名称">
                        <el-option v-for="(item, index) in cusOptions" :key="index" :label="item.company_name"
                            :value="item.user_id">
                            <span style="float: left">{{ item.company_name }}</span>
                            <span style="
                        float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;
                      ">{{ '（' + item.address + '）' }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="被托管方单位编号" :required="false">
                    <el-input disabled style="width:350px" v-model="add_data.trustCompanyNum" placeholder="被托管单位名称">
                    </el-input>
                </el-form-item>

                <el-form-item label="被托管方单位详细地址" :required="false">
                    <el-input disabled style="width:350px" v-model="add_data.trustAddress" placeholder="被托管方单位详细地址">
                    </el-input>
                </el-form-item>

                <el-form-item label="被托管方负责人" :required="false">
                    <el-input disabled style="width:350px" v-model="add_data.trustHeadInfo" placeholder="被托管方负责人">
                    </el-input>
                </el-form-item>

            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import {
    line2treeData

} from '@/utils/common.js'

import {
    adupPrivateSet, getPrivateSetList, findTrusteeshipRecordList, adupTrusteeshipRecord, getCompanyCombo,
    cancelTrusteeshipRecord, delTrusteeshipRecord,

} from '@/api/vehicle_custody.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import CircularJSON from 'circular-json'
onMounted(async () => {


    getPrivateSetList({
        find: '我的托管',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })




    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

        }
    })

    getCompanyCombo({
        companyRole: 'CAR_TEAM',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.code == 1) {
            cusOptions.value = res.data;
            cusOptions2.value = res.data;
        }
    })



    await list_api()

})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '被托管方单位编号', field: 'trustCompanyNum', width: '', off: true },
    { label: '被托管方单位名称', field: 'trustCompanyName', width: '', off: true },
    { label: '被托管方负责人', field: 'trustHeadInfo', width: '', off: true },
    { label: '被托管方单位详细地址', field: 'trustAddress', width: '400', off: true },
    { label: '被托管状态', field: 'trustStatus', width: '', off: true },
    { label: '添加时间', field: 'addTime', width: '190', off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value

}
const resetTableSet = () => {
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '我的托管',
        tbNum: "my_hosting",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
const timeTypeTime = ref([])
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}

const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 200,
    },
    trustCompanyName: '',
    etime: '',
    trustStatusList: [],
    stime: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    findTrusteeshipRecordList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total

    })
}
//#endregion

//#region 添加
const cusOptions = ref([])
const cusOptions2 = ref([])
const cusOptions_handleFilter = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = cusOptions2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            cusOptions.value = results
        } else {
            cusOptions.value = []
        }
    } else {
        cusOptions.value = cusOptions2.value
    }
}

const cusCompany_change = (e) => {
    let data = {}
    for (let i = 0; i < cusOptions2.value.length; i++) {
        if (e == cusOptions2.value[i].user_id) {
            data = cusOptions2.value[i]


            add_data.trustAddress = data.address
            add_data.trustCompanyName = data.company_name
            add_data.trustCompanyNum = data.company_num
            add_data.trustHeadInfo = data.head_name + '-' + data.head_phone
            add_data.trustLngLat = data.lng_lat
            add_data.trustUserId = data.user_id



        }
    }

}


const add_off = ref(false)
const title = ref('添加我的托管')

const add_data = reactive({

    id: '',
    trustAddress: "",
    trustCompanyName: "",
    trustCompanyNum: "",
    trustHeadInfo: "",
    trustLngLat: "",
    trustUserId: "",
})
const add_btn = () => {
    title.value = '添加我的托管'

    add_data.id = ''
    add_data.trustAddress = ''
    add_data.trustCompanyName = ''
    add_data.trustCompanyNum = ''
    add_data.trustHeadInfo = ''
    add_data.trustLngLat = ''
    add_data.trustUserId = ''


    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改我的托管'


    add_data.trustUserId = table_list.value[0].trustUserId
    add_data.trustLngLat = table_list.value[0].trustLngLat
    add_data.trustHeadInfo = table_list.value[0].trustHeadInfo
    add_data.trustCompanyNum = table_list.value[0].trustCompanyNum
    add_data.trustCompanyName = table_list.value[0].trustCompanyName
    add_data.trustAddress = table_list.value[0].trustAddress
    add_data.id = table_list.value[0].id

    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {




    if (title.value == '添加我的托管') {

        adupTrusteeshipRecord(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        adupTrusteeshipRecord(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delTrusteeshipRecord({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}
//#endregion




//#region 单位取消托管申请
const cancelTrusteeshipRecord_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否取消托管申请`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            cancelTrusteeshipRecord({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    // window.location.reload(true);
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}
//#endregion

//#region 搜索
const search_btn = () => {

    list_api()
}
//#endregion

</script>

<style scoped lang='scss'>
.paddingLeft {
    padding-left: 24px;
}

.paddingLeft_3 {
    padding-left: 48px;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
